<template>
  <div class="users-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-button type="primary" @click="handleAddUser">添加用户</el-button>
    </div>
    
    <div class="search-filters">
      <el-input v-model="searchKeyword" placeholder="请输入用户名或邮箱搜索" style="width: 300px; margin-right: 10px;"></el-input>
      <el-select v-model="searchRole" placeholder="选择角色" style="width: 150px; margin-right: 10px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="系统管理员" value="admin"></el-option>
        <el-option label="普通用户" value="user"></el-option>
        <el-option label="访客" value="guest"></el-option>
      </el-select>
      <el-select v-model="searchStatus" placeholder="选择状态" style="width: 150px; margin-right: 10px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="启用" value="active"></el-option>
        <el-option label="禁用" value="inactive"></el-option>
      </el-select>
      <el-button type="default" @click="handleSearch">搜索</el-button>
      <el-button type="default" @click="handleResetFilters">重置</el-button>
    </div>
    
    <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="用户ID" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="250"></el-table-column>
      <el-table-column prop="role" label="角色" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">{{ getRoleLabel(scope.row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.status" 
            active-value="active" 
            inactive-value="inactive" 
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="lastLogin" label="最后登录" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.lastLogin) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" text @click="handleEditUser(scope.row)">编辑</el-button>
          <el-button type="danger" text @click="handleDeleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredUsers.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElButton, ElInput, ElSelect, ElOption, ElTable, ElTableColumn, ElTag, ElSwitch, ElPagination, ElMessage, ElMessageBox, ElLoading } from 'element-plus'

// 模拟用户数据
const users = reactive([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    role: 'admin',
    status: 'active',
    createdAt: '2025-09-28T00:00:00Z',
    lastLogin: '2025-09-28T15:30:00Z'
  },
  {
    id: 2,
    username: 'user1',
    email: 'user1@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2025-09-27T00:00:00Z',
    lastLogin: '2025-09-28T14:20:00Z'
  },
  {
    id: 3,
    username: 'user2',
    email: 'user2@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2025-09-26T00:00:00Z',
    lastLogin: '2025-09-28T10:15:00Z'
  },
  {
    id: 4,
    username: 'guest1',
    email: 'guest1@example.com',
    role: 'guest',
    status: 'inactive',
    createdAt: '2025-09-25T00:00:00Z',
    lastLogin: '2025-09-27T09:45:00Z'
  },
  {
    id: 5,
    username: 'user3',
    email: 'user3@example.com',
    role: 'user',
    status: 'active',
    createdAt: '2025-09-24T00:00:00Z',
    lastLogin: '2025-09-28T08:30:00Z'
  }
])

// 搜索和筛选
const searchKeyword = ref('')
const searchRole = ref('')
const searchStatus = ref('')
const loading = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取角色标签类型
const getRoleTagType = (role: string) => {
  const roleMap: Record<string, string> = {
    'admin': 'primary',
    'user': 'success',
    'guest': 'info'
  }
  return roleMap[role] || 'default'
}

// 获取角色标签文本
const getRoleLabel = (role: string) => {
  const roleMap: Record<string, string> = {
    'admin': '系统管理员',
    'user': '普通用户',
    'guest': '访客'
  }
  return roleMap[role] || role
}

// 筛选用户
const filteredUsers = computed(() => {
  return users.filter(user => {
    // 按关键词搜索（用户名或邮箱）
    const keywordMatch = !searchKeyword.value || 
      user.username.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      user.email.toLowerCase().includes(searchKeyword.value.toLowerCase())
    
    // 按角色筛选
    const roleMatch = !searchRole.value || user.role === searchRole.value
    
    // 按状态筛选
    const statusMatch = !searchStatus.value || user.status === searchStatus.value
    
    return keywordMatch && roleMatch && statusMatch
  })
})

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  // 模拟搜索加载
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 重置筛选条件
const handleResetFilters = () => {
  searchKeyword.value = ''
  searchRole.value = ''
  searchStatus.value = ''
  currentPage.value = 1
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
}

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 添加用户
const handleAddUser = () => {
  ElMessageBox.alert(
    '添加用户功能正在开发中，请稍后再试。',
    '提示',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 编辑用户
const handleEditUser = (user: any) => {
  ElMessageBox.alert(
    `编辑用户功能正在开发中，用户ID：${user.id}，用户名：${user.username}`,
    '提示',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 删除用户
const handleDeleteUser = (user: any) => {
  if (user.username === 'admin') {
    ElMessage.error('系统管理员不能被删除')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除用户「${user.username}」吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    const index = users.findIndex(u => u.id === user.id)
    if (index > -1) {
      users.splice(index, 1)
      ElMessage.success('用户删除成功')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 更改用户状态
const handleStatusChange = (user: any) => {
  if (user.username === 'admin') {
    // 系统管理员状态不能被更改
    user.status = 'active'
    ElMessage.error('系统管理员状态不能被更改')
    return
  }
  
  // 模拟状态更新操作
  const statusText = user.status === 'active' ? '启用' : '禁用'
  ElMessage.success(`用户「${user.username}」已${statusText}`)
}
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-filters {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fafafa;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa !important;
  font-weight: 600;
}

.el-table td {
  border-top: 1px solid #f0f0f0;
}
</style>